package cn.community.system.shiro;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

// Realms 的授权控制
public class UserModularReamAuthorizer extends ModularRealmAuthorizer {

    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {

        // 判断getRealms()是否返回为空
        assertRealmsConfigured();

        // 所有Realms
        Collection<Realm> realms = getRealms();
        HashMap<String, Realm> realmHashMap = new HashMap<>(realms.size());
        for (Realm realm : realms) {
            if (realm.getName().contains("Admin")){
                realmHashMap.put("AdminRealm",realm);
            }else if(realm.getName().contains("Association")){
                realmHashMap.put("AssociationRealm",realm);
            }else if(realm.getName().contains("Member")){
                realmHashMap.put("MemberRealm",realm);
            }
        }

        Set<String> realmNames = principals.getRealmNames();
        if (realmNames != null){
            String realmName = null;
            Iterator<String> it = realmNames.iterator();
            while (it.hasNext()){
                realmName = ConvertUtils.convert(it.next());
                if (realmName.contains("Admin")){
                    return ((AdminRealm)realmHashMap.get("AdminRealm")).isPermitted(principals,permission);
                }else if (realmName.contains("Association")){
                    return ((AssociationRealm)realmHashMap.get("AssociationRealm")).isPermitted(principals,permission);
                }else if (realmName.contains("Member")){
                    return ((MemberRealm)realmHashMap.get("MemberRealm")).isPermitted(principals,permission);
                }
                break;
            }
        }
        return false;
    }
}
